package com.edu.servlet;

import com.edu.bean.Post;
import com.edu.bean.User;
import com.edu.service.UserPostService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/consult/add")
public class UserConsultAddServlet extends HttpServlet {
    private UserPostService postService = new UserPostService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 检查登录状态
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"success\":false,\"message\":\"请先登录\"}");
            return;
        }

        // 获取参数
        String title = request.getParameter("title");
        String content = request.getParameter("content");

        // 参数验证
        if (title == null || title.trim().isEmpty() || content == null || content.trim().isEmpty()) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"success\":false,\"message\":\"标题和内容不能为空\"}");
            return;
        }

        // 创建帖子对象
        Post post = new Post();
        post.setUserId(user.getUserId());
        post.setTitle(title.trim());
        post.setContent(content.trim());
        post.setPostType(2); // 2=心理咨询

        // 保存帖子
        boolean success = postService.userAddPost(post);

        // 返回结果
        response.setContentType("application/json;charset=utf-8");
        if (success) {
            response.getWriter().write("{\"success\":true,\"message\":\"发布成功\"}");
        } else {
            response.getWriter().write("{\"success\":false,\"message\":\"发布失败\"}");
        }
    }
}